package com.af.monitorModule.timmer;

import com.af.monitorModule.generator.entity.SingleValue;
import com.af.monitorModule.generator.mapper.SingleValueMapper;
import com.af.monitorModule.generator.mapper.TimedTaskResultMapper;
import com.af.monitorModule.generator.service.ErrorSendService;
import com.af.monitorModule.util.DayStatisticsImages;
import com.af.monitorModule.util.RestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.util.List;

@Component
public class DaySummary {

    @Autowired
    private ValueOperations<String,Object> valueOperations;

    @Autowired
    private SingleValueMapper singleValueMapper;

    @Autowired
    private TimedTaskResultMapper timedTaskResultMapper;

    @Autowired
    private DayStatisticsImages dayStatisticsImages;

    private static final Logger logger = LoggerFactory.getLogger(CheckHeart.class);

    /**
     * 每日汇总数据
     */
    @Scheduled(cron = "55 59 23 * * ? ")
    public void dataStatistics(){
        JSONObject info = new JSONObject();
        String now = LocalDate.now().toString();
        //逐个获取每日数据
        //Redis 获取
        //每日推送信息推送量
        Object toDaySendMSG = valueOperations.get("toDaySendMSG");
        info.put("toDaySendMSG",toDaySendMSG == null ? 0 : toDaySendMSG);
        //每日服务器上报指标数据量
        Object toDayServerPush = valueOperations.get("toDayServerPush");
        info.put("toDayServerPush",toDayServerPush == null ? 0 : toDayServerPush);
        //每日屏蔽的无用信息推送量
        Object toDayMeaningless = valueOperations.get("toDayMeaningless");
        info.put("toDayMeaningless",toDayMeaningless == null ? 0 : toDayMeaningless);
        //每日自动重启服务数量
        Object toDayServiceRestart = valueOperations.get("toDayServiceRestart");
        info.put("toDayServiceRestart",toDayServiceRestart == null ? 0 : toDayServiceRestart);
        //每日成功防止数据库死锁次数
        Object toDayKillDataBase = valueOperations.get("toDayKillDataBase");
        info.put("toDayKillDataBase", toDayKillDataBase == null ? 0 : toDayKillDataBase);

        //数据库获取
        //每日执行定时任务执行结果
        List<JSONObject> timedTaskSummary = timedTaskResultMapper.getTimedTaskSummary(now);
        for (JSONObject one : timedTaskSummary) {
            info.put(one.getString("result"), one.get("num"));
        }


        //存入单值表
        singleValueMapper.insert(new SingleValue().setName(LocalDate.now().toString() + "Statistics")
                .setValue(info.toJSONString())
                .setRemake("每日数据统计"));


    }

    /**
     * 推送昨晚的总结数据
     */
    @Scheduled(cron = "0 0 9 * * ? ")
    public void sendYesterdayStatistics(){
        String yesterday = LocalDate.now().plusDays(-1).toString();
        SingleValue dingDing = singleValueMapper.selectOne(new QueryWrapper<SingleValue>().eq("name", "运维钉钉"));
        SingleValue daily = singleValueMapper.selectOne(new QueryWrapper<SingleValue>().eq("name", yesterday+"Statistics"));
        if (daily == null){
            logger.error("每日早晨日报推送无内容，检查昨日汇总");
            return;
        }
        //生成昨日汇总图片
        dayStatisticsImages.createDayImages(JSON.parseObject(daily.getValue()));
        //组织推送到钉钉的数据
        LocalDate today = LocalDate.now();
        String data = "{\"msgtype\":\"markdown\",\"markdown\":{\"title\":\"昨日战况\",\"text\":\"### 早上好,看看昨日统计吧： " +
                "\n ![](http://139.9.137.3/file/dayImages/"+yesterday+".png)" +
                "\n ###### "+(today.getMonthValue() + "月" + today.getDayOfMonth() + "日")+"发布\"},\"at\":{\"atMobiles\":[],\"isAtAll\":true}}";
        //推送
        JSONObject back = RestUtil.sendPost(dingDing.getValue(), JSONObject.class, JSON.parseObject(data));
        logger.info("每日早晨日报推送返回结果：" + back);
        System.gc();
    }

}

